package jn.chen.utils;

import com.sun.istack.internal.NotNull;

import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Properties;

/**
 * @className: MailUtil
 * @author: chenLin
 * @version: 1.0.0
 * @description:
 * @date: 2022/10/8 14:50
 * 邮件发送测试代码
 */
public class MailUtil {

    /**
     * @param sendEMail 发送者邮箱号
     * @param sendSubject 邮件主题
     * @param toFroMer 接收者邮箱号
     * @param message  邮箱内容
     * @param connectPassWord  邮箱认证密码
     */
    public static void sendMail(@NotNull() String sendEMail,
                                @NotNull() String sendSubject,
                                @NotNull() String toFroMer,
                                @NotNull() String message,
                                @NotNull() String connectPassWord) {
        // 创建map TODO
        Properties properties = new Properties();
        properties.put("mail.transport.protocol", "smtp");
        properties.put("mail.smtp.host", "smtp.qq.com");

        Session instance = Session.getInstance(properties);

        // 创建虚拟邮件对象
        try {
            MimeMessage mimeMessage = new MimeMessage(instance);
            mimeMessage.setFrom(new InternetAddress(sendEMail));
            mimeMessage.setRecipient(MimeMessage.RecipientType.BCC, new InternetAddress(toFroMer));
            mimeMessage.setSubject(sendSubject);
            mimeMessage.setSentDate(new Date());
            mimeMessage.setText(message);
            mimeMessage.saveChanges();

            Transport transport = instance.getTransport();
            //获得认证
            transport.connect(sendEMail, connectPassWord);
            transport.sendMessage(mimeMessage,mimeMessage.getAllRecipients());
            transport.close();
            System.out.println("发送邮件成功");
        } catch (MessagingException e){
            e.printStackTrace();
        }

    }
}
